// https://www.lintcode.com/problem/binary-tree-level-order-traversal/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    public List<List<Integer>> levelOrder(final TreeNode root) {
        // write your code here
        List<List<Integer>> ret = new ArrayList<>();
        ArrayList<TreeNode>[] arrays = new ArrayList[]{new ArrayList<TreeNode>(), new ArrayList<TreeNode>() };
        int curr = 0;
        if (root != null) {
            arrays[curr].add(root);
            while (arrays[curr].size() > 0) {
                int next = 1 - curr;
                List<Integer> level = new ArrayList<>();
                for (TreeNode node : arrays[curr]) {
                    level.add(node.val);
                    if (node.left != null) {
                        arrays[next].add(node.left);
                    }
                    if (node.right != null) {
                        arrays[next].add(node.right);
                    }
                }
                arrays[curr].clear();
                curr = next;
                ret.add(level);
            }
        }
        return ret;
    }
}